package com.elong.android.specialhouse.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.entity.BookRequestParam;
import com.elong.android.specialhouse.request.CreateOrderReq;
import com.elong.android.specialhouse.ui.AddSubView;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.EVerifyString;
import com.elong.android.specialhouse.utils.ElongValidator;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.android.specialhouse.utils.InputFilterUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.android.specialhouse.utils.filter.BaseFilter;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.payment.utils.MathUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AskForBookingActivity extends BaseVolleyActivity<IResponse<?>> implements View.OnClickListener {
    public static final String TAG = "com.elong.android.youfang.activity.AskForBookingActivity";
    private static final String PAGE_NAME = "youfangOrderFilledPage";
    public static final int DEFAULT_MAX = 15;

    private EditText etCheckInPerson;
    private EditText etMessageToLandlord;

    private TextView tvCheckInTime;
    private TextView tvCheckInTotalDays;
    private TextView tvTotalPrice;
    private TextView tvRoomCharge;
    private TextView tvServerCharge;
    private TextView tvSubmit;
    private AddSubView addSubView;
    private Intent mIntent;
    /**
     * 创建订单请求参数的model
     */
    private CreateOrderReq mCreateOrderReqParam;

    private String mApartmentName;
    private int mMaxPeopleNum;

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_ask_for_booking);
        initView();
    }

    private void initView() {
        setHeader(R.string.ask_for_booking_title);
        etCheckInPerson = (EditText) findViewById(R.id.et_checkin_person);
        etMessageToLandlord = (EditText) findViewById(R.id.et_leave_msg_to_landlord);
        tvCheckInTime = (TextView) findViewById(R.id.tv_checkin_time);
        tvCheckInTotalDays = (TextView) findViewById(R.id.tv_checkin_total_days);
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        tvRoomCharge = (TextView) findViewById(R.id.tv_room_charge);
        tvServerCharge = (TextView) findViewById(R.id.tv_server_charge);
        tvSubmit = (TextView) findViewById(R.id.tv_submit);
        addSubView = (AddSubView) findViewById(R.id.add_sub_view_checkin_people_num);

        setListener();
    }

    private void setListener() {
        tvSubmit.setOnClickListener(this);
        addSubView.setOnClickListener(this);
        //现在的需求是 预订页不准修改日期,下面一行代码暂时注释
//        tvCheckInTime.setOnClickListener(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventReportTools.sendPageOpenEvent(PAGE_NAME);
        initData();
    }

    private void initData() {
        addSubView.setEditTextEnable(true);
        //填充默认入住人
        setDefaultCheckinPerson();
        //控制入住人只能输入汉字或者英文
        ElongValidator.CanOnlyInputZhAndEn(etCheckInPerson);
        //过滤表情
//        etMessageToLandlord.setFilters(new InputFilter[]{InputFilterUtils.getEmojiInputFilter()});

        mCreateOrderReqParam = new CreateOrderReq();
        mIntent = getIntent();
        BookRequestParam reqParam = (BookRequestParam) mIntent.getSerializableExtra(AppConstants.ACTIVITY_KEY_BOOK_REQUEST_PARAM);

        mApartmentName = reqParam.apartmentName;
        //设置房东允许的最大入住人数
        mMaxPeopleNum = reqParam.maxPeopleNum;
//        if (mMaxPeopleNum != -1) {
//            addSubView.setMax(mMaxPeopleNum);
//        }

        showCheckInTimeOnTextView(reqParam.checkInDate, reqParam.checkOutDate, reqParam.totalDays);
        mCreateOrderReqParam.roomCharge = MathUtils.doubleFormat(reqParam.totalRoomPrice);
        mCreateOrderReqParam.serviceCharge = MathUtils.doubleFormat(reqParam.totalServicePrice);
        mCreateOrderReqParam.sumPrice = MathUtils.doubleFormat(reqParam.sumPrice);
        mCreateOrderReqParam.houseId = reqParam.houseId + "";

        mCreateOrderReqParam.ruleType = reqParam.isCanCancel;
        mCreateOrderReqParam.ruleContent = reqParam.cancelRulesInner;
        mCreateOrderReqParam.userId = Account.getInstance().getUserId();

        mCreateOrderReqParam.outerOrigin = AppConstants.OUTER_ORIGIN;

        tvTotalPrice.setText("￥" + mCreateOrderReqParam.sumPrice);
        tvRoomCharge.setText("含房费：￥" + mCreateOrderReqParam.roomCharge);
        tvServerCharge.setText("服务费：￥" + mCreateOrderReqParam.serviceCharge);
    }

    /**
     * 显示入住及离店时间
     */
    private void showCheckInTimeOnTextView(Calendar arriveDate, Calendar leaveDate, long totalDays) {
        mCreateOrderReqParam.totalDays = totalDays;
        SimpleDateFormat sdf1 = new SimpleDateFormat("M月d日", Locale.CHINA);
        Calendar currCalender = DateTimeUtils.getCurrentDateTime();
        currCalender.add(Calendar.HOUR_OF_DAY, -6);
        if (arriveDate.after(currCalender) && arriveDate.before(leaveDate)) {
            String inTime = sdf1.format(arriveDate.getTime());
            String outTime = sdf1.format(leaveDate.getTime());
            tvCheckInTime.setText(inTime + "—" + outTime);
            tvCheckInTotalDays.setText("(共" + totalDays + "晚)");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            mCreateOrderReqParam.arriveDate = sdf2.format(arriveDate.getTime());
            mCreateOrderReqParam.leaveDate = sdf2.format(leaveDate.getTime());
        }

    }

    /**
     * 填充成单请求参数
     */
    private void setUpCreateOrderReq() {
        mCreateOrderReqParam.customerCount = addSubView.getCount();
        mCreateOrderReqParam.customerName = etCheckInPerson.getText().toString().trim();
        mCreateOrderReqParam.messageToLandlord = etMessageToLandlord.getText().toString().trim();
        mCreateOrderReqParam.traceId = Utils.generateTraceId();
    }

    /**
     * 默认填充入住人是用户的姓名
     */
    private void setDefaultCheckinPerson() {
        if (Account.getInstance().isLogin()) {
            etCheckInPerson.setText(Account.getInstance().getNickName());
            etCheckInPerson.setSelection(etCheckInPerson.getText().toString().trim().length());
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_submit:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "submit");//提交submit
                int num = etMessageToLandlord.getText().toString().trim().length();
                EventReportTools.sendOrderMessageInfoEvent(PAGE_NAME, num + "");//留言字数
                //填充请求信息
                setUpCreateOrderReq();
                validate();
                break;
            case R.id.add_sub_view_checkin_people_num:
                addSubView.getCountEditText().requestFocus();
//                int count = addSubView.getCount();
//                if (count > mMaxPeopleNum) {
//                    DialogUtils.showInfo(this, "", getString(R.string.checkin_people_num_out_of_max));
//                }
                break;
            default:
                break;
        }
    }
    @Override
    public void back(){
        EventReportTools.sendPageSpotEvent(PAGE_NAME, "back");//返回back
        super.back();
    }
    private void validate() {
        if (StringUtils.isEmpty(mCreateOrderReqParam.customerName)) {
            ToastUtils.show(this, R.string.please_input_check_in_person);
            return;
        }
        int count = addSubView.getCount();
        if (count <= 0) {
            ToastUtils.show(this, R.string.please_input_check_in_person_num);
            return;
        }
        if (mMaxPeopleNum != -1 && mMaxPeopleNum < DEFAULT_MAX + 1) {
            //不等于-1且小于DEFAULT_MAX + 1表示房东设置了最大入住人数，否则则说明房东不限制入住人数
            if (count > mMaxPeopleNum) {
                DialogUtils.showInfo(this, "", getString(R.string.checkin_people_num_out_of_max));
                return;
            }
        }
        if (EVerifyString.containsLimitedWordsAndSymbol(mCreateOrderReqParam.customerName)) {
            ToastUtils.show(this, R.string.check_in_person_cannont_contains_sensitive_word);
            return;
        }
        if (!ElongValidator.isCheckInPerson(mCreateOrderReqParam.customerName)) {
            ToastUtils.show(this, R.string.check_in_person_formatter_wrong);
            return;
        }

        if (InputFilterUtils.containsSensitiveWords(mCreateOrderReqParam.messageToLandlord, this)) {
            DialogUtils.showInfo(this, R.string.warning, R.string.malicious_tips);
        }
        mCreateOrderReqParam.messageToLandlord = new BaseFilter(mCreateOrderReqParam.messageToLandlord).execute();

        if (mCreateOrderReqParam.messageToLandlord.length() > 80) {
            ToastUtils.show(this, R.string.leave_msg_can_not_over_80);
            return;
        }

        if (!Account.getInstance().isLogin()) {
            goToLoginPage();
            return;
        }
        // 验证成功后才提交
        submit();
    }

    private void submit() {
        CreateOrderReq req = mCreateOrderReqParam;
        requestHttp(req, ApartmentAPI.createOrder, StringResponse.class, true);
    }


    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        ApartmentAPI action = (ApartmentAPI) request.getRequestOption().getHusky();
        JSONObject result = null;
        try {
            result = JSON.parseObject(((StringResponse) t).getContent());
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.show(this, R.string.parse_error);
        }
        if (result == null) {
            ToastUtils.show(this, R.string.server_not_responding);
            return;
        }

        //过滤错误信息
        if (handleIsError(request, result)) {
            return;
        }
        switch (action) {
            case createOrder:
                // 提交成功后跳到申请已提交界面
                String gorderId = result.getString(AppConstants.GORDER_ID);
                String orderId = result.getString(AppConstants.ORDER_ID);
                if (TextUtils.isEmpty(orderId)) {
                    orderId = gorderId;
                }
                goToBookingSubmitedPage(gorderId, orderId);
                break;
        }
    }

    /**
     * 跳到申请已提交页
     */
    private void goToBookingSubmitedPage(String gorderId, String orderId) {
        Intent intent = new Intent(this, BookingSubmitedActivity.class);
        intent.putExtra(AppConstants.GORDER_ID, gorderId);
        intent.putExtra(AppConstants.ORDER_ID, orderId);
        intent.putExtra(AppConstants.APARTMENT_NAME, mApartmentName);
        intent.putExtra(AppConstants.ORDER_REQ_PARAMS, mCreateOrderReqParam);
        startActivity(intent);
        finish();
    }

    /**
     * 跳到登录页
     */
    private void goToLoginPage() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
        startActivity(intent);
    }
}
